package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.FollowBehaviorConstants;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.feign.ApAuthorFeign.ArticleFeign;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import com.sun.xml.bind.v2.model.core.ID;
import org.bouncycastle.crypto.tls.DTLSProtocol;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    ArticleFeign articleFeign;

    @Autowired
    ApUserFanMapper apUserFanMapper;

    @Autowired
    ApUserFollowMapper apUserFollowMapper;


    /**
     * 关注或取消关注
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //因为前端传来的是一个null 并没有作者id 因为这个需求是他妈的一个假的
        //我们为了他妈的测试 给他他妈的赋上一个数据库有的作者id值
        if (dto.getAuthorId()==null){
            dto.setAuthorId(4);
        }

        //登录用户的id  要关注别人的那个人的id 在粉丝表里 他是粉丝id
        Integer loginId = AppThreadLocalUtils.getUser().getId();
        if (loginId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //发布文章的作者
        ApAuthor apAuthor = articleFeign.findById(dto.getAuthorId());
        if (apAuthor == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"未找到该用户！");
        }

        //authorUserId是作者用户id
        Integer authorUserId = apAuthor.getUserId();

        if (dto.getOperation().equals((short) 0)) {
            //关注
            //关注要判断是否已经关注
            ResponseResult responseResult = saveFanAndFollow(loginId, authorUserId,apAuthor.getName(),dto.getArticleId());
            if (!responseResult.getCode().equals((Integer)0)){
                return responseResult;
            }
        } else {
            //取关
            delFanAndFollow(loginId, authorUserId);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 取关
     * @param loginId
     * @param authorUserId
     */
    private void delFanAndFollow(Integer loginId, Integer authorUserId) {
        //authorUserId  是文章发布者的用户id
        //loginId   是当前登录人的用户id

        //删除粉丝表
        apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getUserId, authorUserId)
                .eq(ApUserFan::getFansId, loginId));

        //删除关注表
      apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
              .eq(ApUserFollow::getUserId, loginId)
              .eq(ApUserFollow::getFollowId, authorUserId));
    }
@Autowired
    KafkaTemplate kafkaTemplate;

    /**
     * 关注用户
     *
     * @param loginId
     * @param authorUserId
     */
    private ResponseResult saveFanAndFollow(Integer loginId, Integer authorUserId,String name,Long articleId) {
        //authorUserId  是文章发布者的用户id
        //loginId   是当前登录人的用户id
        //name 是文章发布者的作者name  关注表里要的是用户name 不过都一样


        //首先判断是否已经关注
        ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId, authorUserId)
                .eq(ApUserFan::getFansId, loginId));
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, loginId)
                .eq(ApUserFollow::getFollowId, authorUserId));
        if (apUserFan != null || apUserFollow != null) {
            //粉丝表和关注表 有一个建立了关系 就是已经关注了 返回 已经关注
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "不能重复关注！");
        }
        ApUserFan fan = new ApUserFan();
        fan.setCreatedTime(new Date());
        fan.setUserId(authorUserId);
        fan.setFansId(loginId.longValue());
        fan.setLevel((short) 0);
        fan.setIsDisplay(true);
        fan.setIsShieldComment(false);
        fan.setIsShieldLetter(false);
        apUserFanMapper.insert(fan);

        ApUserFollow follow = new ApUserFollow();
        follow.setFollowName(name);
        follow.setCreatedTime(new Date());
        follow.setUserId(loginId);
        follow.setFollowId(authorUserId);
        follow.setLevel((short) 1);
        follow.setIsNotice(true);
        apUserFollowMapper.insert(follow);

        //同步到行为微服务的 关注行为
        Integer id = AppThreadLocalUtils.getUser().getId();
        FollowBehaviorDto dto = new FollowBehaviorDto();
        dto.setArticleId(articleId);
        dto.setFollowId(authorUserId);
        dto.setUserId(id);
        String dtoStr = JSON.toJSONString(dto);
        kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC,dtoStr);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
